package com.oneraku.service.utils;

import com.alibaba.fastjson.annotation.JSONField;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;

import java.time.LocalDateTime;
import java.util.Collections;

/**
 * @Author: hui.ren@huberbuy.com
 * @Date: 2020/1/10 14:22
 */
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class R {
    private long code;
    private String message;
    private Object body;
    private Long count;
    private String requestId = RequestBeanUtils.get().getRequestId();

    @JSONField(format="yyyy-MM-dd HH:mm:ss")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime timestamp = LocalDateTime.now();

    public static  R ok(Object t){
        R result = new R();
        result.setCode(ResultCode.OK.getCode());
        result.setMessage(ResultCode.OK.getMsg());
        result.setBody(t);
        return result;
    }
    public static  R okPage(IPage t){
        R result = new R();
        result.setCode(ResultCode.OK.getCode());
        result.setMessage(ResultCode.OK.getMsg());
        result.setBody(t.getRecords());
        result.setCount(t.getTotal());
        return result;
    }
    public static  R okEmptyPage(){
        R result = new R();
        result.setCode(ResultCode.OK.getCode());
        result.setMessage(ResultCode.OK.getMsg());
        result.setBody(Collections.emptyList());
        result.setCount(0L);
        return result;
    }
    public static  R failed(ResultCode code){
        R result = new R();
        result.setCode(code.getCode());
        result.setMessage(code.getMsg());
        return result;
    }
    public static  R failed(String msg){
        R result = new R();
        result.setCode(ResultCode.HTTP_ERROR_400.getCode());
        result.setMessage(msg);
        return result;
    }
}
